package com.hmsm.sys.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.bcel.generic.GETSTATIC;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.taglibs.standard.tag.common.core.SetSupport;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hmsm.server.common.CommonUtil;
import com.hmsm.server.util.URLHelp;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.service.SysConfigService;
import com.hmsm.sys.service.UserInfoService;

@Controller("rtxLoginController")
@Scope("prototype")
@RequestMapping("/")
public class RtxLoginController {

	private static final Log log = LogFactory.getLog(RtxLoginController.class);
	
	public static String RTX_URL = "rtxurl";
	
	public static String RTX_URL_DEFAULT = "http://rtx.lxls.net:8012/SignAuth.cgi";
	
	@Resource
	private SysConfigService sysConfigService;
	
	public SysConfigService getSysConfigService() {
		return sysConfigService;
	}

	@Resource
	private UserInfoService userInfoService;
	
	public UserInfoService getUserInfoService() {
		return userInfoService;
	}

	public ModelAndView login(String rtxuser, String sign, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView();

		if(rtxuser!=null&&sign!=null){
			boolean result = validateRtxLogin(rtxuser, sign); 
			UserInfo userInfo = null;
			if(result){
				
				String accountSource = "RTX_001";
				try {
					userInfo = getUserInfoService().getByUserName(rtxuser);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(userInfo==null){
					userInfo = getUserInfoService().getByRelevanceUserName(accountSource, rtxuser);
				}
				if(userInfo!=null){
					userInfo = getUserInfoService().login(userInfo.getUserName(), null);
					modelAndView.getModel().put("currentUser", userInfo);
					request.getSession().setAttribute("user", userInfo);
				}else{
					result = false;
				}
			}else{
				
			}
			
			Map<String, Object> mapResult = modelAndView.getModel();
			mapResult.put("success", result);
			mapResult.put("currentUser", userInfo);
			if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
				// ajax 调用
				modelAndView.setViewName("json");
			}else{
				// 非 ajax 调用
				if(result){
					modelAndView.setViewName("success");
				}else{
					modelAndView.setViewName("failed");
				}
			}
		}else{
			modelAndView.setViewName("input");
		}
		
		return modelAndView;
	}

	private boolean validateRtxLogin(String rtxuser, String sign) {
		boolean result = false;
		
		String charsetName = "GBK";
		String strAccount = null;
		String strSign = null;
		
		// 提供了标准在线令牌，进行在线验证
		try {
			strAccount = URLEncoder.encode(rtxuser, charsetName);
			strSign = URLEncoder.encode(sign, charsetName);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		if (strAccount!=null){
			String rtxUrl = getRtxUrl()+"?"+"user=" + strAccount + "&"+"sign=" + strSign;
			
			String strResult = new URLHelp().postURL(rtxUrl, null, charsetName);
			result = "success!".equalsIgnoreCase(strResult); 
		}
		
		return result;
	}

	private String getRtxUrl() {
		String rtxUrl = CommonUtil.getSysConfigMap().get(RTX_URL);
		if (rtxUrl==null) {
			rtxUrl = RTX_URL_DEFAULT;
			try {
				getSysConfigService().save(RTX_URL, rtxUrl, "腾讯通地址");
				getSysConfigService().refreshSysConfig();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rtxUrl;
	}

}
